/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 用户反馈-快递员
 *  */
import React, { useEffect, useRef, useState } from 'react';
import ProList from '@ant-design/pro-list';
import { Space, Row, Col, Image, message, Button, Modal, Form, Input, Popconfirm } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { getCourierList, courierSave } from '@/services/feedback/courier';
import { random } from 'lodash';
import { useLocation, useSelector } from 'umi';
import type { Location } from 'umi';
import type { ConnectState } from '@/models/connect';
import type { ActionType } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { ListItem } from '@/pages/HandleFeedback/courier/index.d';
import checkFileSize from '../utils';
import styles from './index.less';
import UploadWithCrypto from '@base/components/upload-width-crypto';

const wxNumber = ['kuaibao168', 'kuaibao66', 'kuaibao77', 'kuaibao99'];

interface FeedBackProps {
  type: string;
  activeKey: string;
}

const Index: React.FC<FeedBackProps> = ({ activeKey, type }) => {
  const { query: { id: queryId = '' } = {} } = useLocation() as Location;
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [visible, setVisible] = useState<boolean>(false);
  const [filesList, setFilesList] = useState<any[]>([]);
  const [record, setRecord] = useState<any>({});
  const [status, setStatus] = useState<number>(2);

  const handleChange = (file: any) => {
    const { fileList } = file;
    if (filesList.length > fileList.length) {
      setFilesList(fileList);
    }
  };

  const onSuccess = (data: any) => setFilesList([...filesList, { url: data.data }]);
  const handleOk = () => formRef.current?.submit();
  const handleModalChancel = () => setVisible(false);

  const onSubmit = async (values: any) => {
    const { id } = record;
    const imgList = filesList.map((item: any) => item.url);
    const res = await courierSave({
      id: id || values.id,
      reply: values.reply,
      status: status,
      reply_images: JSON.stringify(imgList),
    });
    const { code, msg } = res;
    if (code == 0) {
      actionRef.current?.reload();
      setVisible(false);
      setFilesList([]);
      setRecord({});
      setStatus(2);
    } else {
      actionRef.current?.reload();
      message.error(msg);
    }
    return res;
  };

  const handleReply = (data: any) => {
    setStatus(1);
    if (data.id) {
      setRecord(data);
    } else {
      setRecord({});
    }
    setVisible(true);
  };

  const handleIgnore = (data: any) => {
    setStatus(2);
    const formData = {
      id: data.id,
      reply: `亲，您的问题描述的不够清晰，客服无法解答，如有疑问请加客服微信：${
        wxNumber[random(3, false)]
      }`,
    };
    onSubmit(formData);
  };

  useEffect(() => {
    if (activeKey !== type) return;
    actionRef.current?.reload();
  }, [activeKey, type]);

  return (
    <>
      <ProList<ListItem>
        className={styles.main}
        actionRef={actionRef}
        rowKey={(row) => row.id}
        pagination={{
          pageSize: 20,
          showSizeChanger: false,
        }}
        itemLayout='vertical'
        split
        showActions='always'
        request={async (params) => {
          const { current, pageSize } = params;
          const reply_type = ['reviewed', 'pass', 'refuse'].indexOf(activeKey);
          return getCourierList({ page: current, pageSize, status: reply_type, id: queryId });
        }}
        metas={{
          title: {
            dataIndex: 'phone',
            editable: false,
            render: (text, row) => {
              return (
                <>
                  <div style={{ marginRight: 20 }}>联系人：{row.phone}</div>
                  <div className={styles.title}>
                    <span style={{ marginRight: 20 }}>版本信息：{row.app}</span>
                    <span style={{ marginRight: 20 }}>{row.update_at}</span>
                  </div>
                </>
              );
            },
          },
          content: {
            dataIndex: 'reply',
            valueType: 'textarea',
            render: (text, row) => {
              if (text === '-' || activeKey === 'reviewed') {
                return null;
              }
              return (
                <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
                  <div>{row.reply_user} 回复：</div>
                  <div>{text}</div>
                  <Space>
                    {row.reply_images.length > 0
                      ? row.reply_images.map((item: string, index: number) => {
                          return <Image width={40} height={40} key={index} src={item}></Image>;
                        })
                      : null}
                  </Space>
                </Space>
              );
            },
          },
          description: {
            valueType: 'textarea',
            dataIndex: 'content',
            editable: () => true,
            render: (text, row) => {
              return (
                <Space>
                  <div className={styles.content}>投诉内容：{text}</div>
                  {row.images.length > 0
                    ? row.images.map((item: string, index: number) => {
                        return <Image width={40} height={40} key={index} src={item}></Image>;
                      })
                    : null}
                </Space>
              );
            },
          },
          actions: {
            render: (text, row) =>
              activeKey !== 'pass' && activeKey !== 'refuse' ? (
                <Row gutter={[20, 20]}>
                  {row.status == '0' && (
                    <>
                      <Col>
                        <Button type='primary' onClick={handleReply.bind(this, row)} key='link'>
                          回复
                        </Button>
                      </Col>
                      <Col>
                        <Popconfirm
                          title='确定忽略？'
                          onConfirm={handleIgnore.bind(this, row)}
                          key='link'
                        >
                          <Button>忽略</Button>
                        </Popconfirm>
                      </Col>
                    </>
                  )}
                </Row>
              ) : null,
          },
        }}
      />
      <Modal
        visible={visible}
        title='意见反馈'
        destroyOnClose
        onCancel={handleModalChancel}
        onOk={handleOk}
      >
        <Form ref={formRef} onFinish={onSubmit}>
          <Form.Item
            name='reply'
            label='反馈内容'
            rules={[{ required: true, message: '请输入反馈内容' }]}
          >
            <Input.TextArea placeholder='请输入内容' maxLength={200} showCount allowClear />
          </Form.Item>
          <Form.Item
            name='files'
            label='上传素材'
            help='点击上传，最多上传3张'
            style={{ marginLeft: 10 }}
            validateTrigger={filesList}
          >
            <UploadWithCrypto
              action='/courier/replyUpload'
              listType='picture-card'
              accept='.jpg,.png'
              multiple={false}
              fileList={filesList}
              onChange={handleChange}
              onSuccess={onSuccess}
              beforeUpload={checkFileSize}
              showUploadList={{ showPreviewIcon: false }}
            >
              {filesList.length >= 3 ? null : (
                <div style={{ color: '#4ca4f8' }}>
                  <PlusOutlined />
                </div>
              )}
            </UploadWithCrypto>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default Index;
